package com.dongjiantong.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by mz03 on 2017/5/11.
 */
public class MD5Util {

    public static String encrypt(String password) {
        try {
            byte[] strTemp = password.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            StringBuilder hexValue = new StringBuilder();
            for (int i = 0; i < md.length; i++) {
                byte aMd = md[i];
                int val = ((int) aMd) & 0xff;
                if (val < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public static boolean match(String password, String encryptedPassword) {
        try {
            byte[] strTemp = password.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            StringBuilder hexValue = new StringBuilder();
            for (byte aMd : md) {
                int val = ((int) aMd) & 0xff;
                if (val < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString().equals(encryptedPassword);
        } catch (NoSuchAlgorithmException e) {
            return false;
        }
    }
    public static void main(String[] args) {
       String password =   encrypt("xyz123456");
        System.out.println("password="+password);

    }
}
